﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using ShopManagement.Dao;
using ShopManagement.Common;
using System.Linq;
using System.Data;
using System.IO;

namespace ShopManagement.Forms
{
    public partial class MainForm : Form
    {
        #region Attributes

        private readonly SmDao myDao;
        private int _role;

        #endregion

        #region Methods

        public MainForm()
        {
            InitializeComponent();
        }

        public MainForm(SmDao inputDao, int role)
        {
            InitializeComponent();
            myDao = inputDao;
            _role = role;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            ReloadData();
            ChangeVisibleControls(false);
        }

        private void btAdd_Click(object sender, EventArgs e)
        {
            ProductForm subForm = new ProductForm(myDao);
            subForm.ShowDialog();
            ReloadData();
        }

        private void btEdit_Click(object sender, EventArgs e)
        {
            try
            {
                string pdCode = dtGridProducts.SelectedRows[0].Cells[1].Value.ToString();
                Product myPd = new Product();
                if (String.IsNullOrEmpty(pdCode))
                {
                    MessageBox.Show("Hãy Chọn Một Sản Phẩm!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    myPd = myDao.GetAProduct(pdCode);
                    ProductForm subForm = new ProductForm(myDao, myPd);
                    subForm.ShowDialog();
                    ReloadData();
                }
            }
            catch(Exception ex)
            {
                
            }
        }

        private void btDel_Click(object sender, EventArgs e)
        {
            try
            {
                if (
                    MessageBox.Show("Bạn Có Chắc Chắn Muốn Xóa!", "Warning", MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    List<string> pdCodes = new List<string>();
                    for (int i = 0; i < dtGridProducts.SelectedRows.Count; i++)
                    {
                        pdCodes.Add(dtGridProducts.SelectedRows[i].Cells[1].Value.ToString());
                    }
                    if (pdCodes.Count > 0)
                    {
                        myDao.DeleteProducts(pdCodes);
                    }
                    ReloadData();
                }
            }
            catch(Exception ex){}
        }

        private void btAddOrder_Click(object sender, EventArgs e)
        {
            OrderForm orderForm = new OrderForm(myDao);
            orderForm.ShowDialog();
            ReloadData();
        }

        private void ReloadData()
        {
            dtGridProducts.DataSource = myDao.GetProducts();
            Utility.TransformProductTable(ref dtGridProducts,_role);
            dtGridProducts.Show();
            dtGridOrders.DataSource = myDao.GetOrders();
            Utility.TransformOrderTable(ref dtGridOrders);
            dtGridOrders.Show();
        }

        private void btUpdateOrder_Click(object sender, EventArgs e)
        {
            try
            {
                string orderNo = dtGridOrders.SelectedRows[0].Cells[0].Value.ToString();
                Order myOrder = new Order();
                if (String.IsNullOrEmpty(orderNo))
                {
                    MessageBox.Show("Hãy Chọn Một Đơn Hàng!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    myOrder = myDao.GetAOrder(int.Parse(orderNo));
                    OrderForm myForm = new OrderForm(myDao, myOrder);
                    myForm.ShowDialog();
                    ReloadData();
                }
            }
            catch(Exception ex){}
        }

        private void btDelOrder_Click(object sender, EventArgs e)
        {
            try
            {
                if (
                    MessageBox.Show("Bạn Có Chắc Chắn Muốn Xóa!", "Warning", MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    Dictionary<string, string> orderCodes = new Dictionary<string, string>();
                    for (int i = 0; i < dtGridOrders.SelectedRows.Count; i++)
                    {
                        orderCodes.Add(dtGridOrders.SelectedRows[i].Cells[0].Value.ToString(),
                                       dtGridOrders.SelectedRows[i].Cells[2].Value.ToString());
                    }
                    foreach (string orderCode in orderCodes.Keys)
                    {
                        Order temp = myDao.GetAOrder(int.Parse(orderCode));
                        if (temp.Status == Constants.OrderStatus.New)
                        {
                            Product tempPd = myDao.GetAProduct(orderCodes[orderCode]);
                            tempPd.Sold = tempPd.Sold - temp.Quantity;
                            myDao.UpdateProduct(tempPd);
                            myDao.DeleteOrders(int.Parse(orderCode));
                        }
                        else
                        {
                            myDao.DeleteOrders(int.Parse(orderCode));
                        }
                    }
                    ReloadData();
                }
            }
            catch(Exception ex){}
        }

        private void dtPickerFrom_ValueChanged(object sender, EventArgs e)
        {
            txtFrom.Text = dtPickerFrom.Value.ToString(Constants.FullYearToDate);
        }

        private void dtPickerTo_ValueChanged(object sender, EventArgs e)
        {
            txtTo.Text = dtPickerTo.Value.ToString(Constants.FullYearToDate);
        }

        private void ChangeVisibleControls(bool status)
        {
            lbRsTitle.Visible = status;
            lbRevenue.Visible = status;
            lbList.Visible = status;
            lbRemain.Visible = status;
            lbSold.Visible = status;
            txtRevenue.Visible = status;
            txtSold.Visible = status;
            txtRemain.Visible = status;
            dtStatisticGrid.Visible = status;
            btExport.Visible = status;
        }

        private void btOk_Click(object sender, EventArgs e)
        {
            if(String.IsNullOrEmpty(txtFrom.Text)|| String.IsNullOrEmpty(txtTo.Text))
            {
                MessageBox.Show("Hãy Chọn Khoảng Thời Gian", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                ChangeVisibleControls(true);
                lbRsTitle.Text = String.Format(Constants.Messages.ResultTitle, txtFrom.Text, txtTo.Text);
                DataSet pdDataSet = new DataSet();
                DataSet orDataSet = new DataSet();
                List<Product> RemainPdList = myDao.GetRemainProducts(ref pdDataSet);
                List<Order> OrderList = myDao.GetOrdersWithTimeConditions(dtPickerFrom.Value, dtPickerTo.Value,
                                                                          ref orDataSet);
                int revenue = 0;
                int soldQuantity = 0;
                int remain = 0;
                foreach (Order tmpOrder in OrderList)
                {
                    revenue += tmpOrder.Profit*tmpOrder.Quantity;
                    soldQuantity += tmpOrder.Quantity;
                }
                foreach (Product tmpProducts in RemainPdList)
                {
                    remain += tmpProducts.Quantity - tmpProducts.Sold;
                }

                txtRevenue.Text = revenue.ToString();
                txtSold.Text = soldQuantity.ToString();
                txtRemain.Text = remain.ToString();
                dtStatisticGrid.DataSource = pdDataSet.Tables[0];
                Utility.TransformProductTable(ref dtStatisticGrid,_role);
                dtStatisticGrid.Show();
            }
        }

        private void btExport_Click(object sender, EventArgs e)
        {
            int counter = 1;
            DataSet orDataSet = new DataSet();
            List<Order> OrderList = myDao.GetOrdersWithTimeConditions(dtPickerFrom.Value, dtPickerTo.Value,ref orDataSet);
            string fileName = Utility.GetPathToCurrentFolder() + Constants.ReportFolder +
                              String.Format(Constants.ReportFileName, DateTime.Now.ToString(Constants.FileNameDateFormat));
            string parentDir = Utility.GetPathToCurrentFolder() + Constants.ReportFolder;
            if(!Directory.Exists(parentDir))
            {
                Directory.CreateDirectory(parentDir);
            }
            TextWriter myWriter = new StreamWriter(fileName,false);
            //Start
            myWriter.WriteLine("======================={0}=======================",DateTime.Now.ToString(Constants.FullYearToSecond));
            myWriter.WriteLine(lbRsTitle.Text);
            myWriter.WriteLine("Doanh Thu: " + txtRevenue.Text);
            myWriter.WriteLine("Doanh Số: " + txtSold.Text);
            myWriter.WriteLine("Các Đơn Hàng Đã Hoàn Thành");
            foreach (Order temp in OrderList)
            {
                myWriter.WriteLine("<------"+counter+"------>");
                writeOrderToFile(myWriter,temp);
                counter++;
            }
            //End
            myWriter.WriteLine("***********************{0}***********************", DateTime.Now.ToString(Constants.FullYearToSecond));
            myWriter.Close();
            MessageBox.Show("Đã Ghi Thành Công Ra File: " + fileName, "Thông Báo", MessageBoxButtons.OK,
                            MessageBoxIcon.Information);
        }

        private void writeOrderToFile(TextWriter myWriter, Order myOrder)
        {
            myWriter.WriteLine("Tên Khách Hàng: "+myOrder.CustomerName);
            myWriter.WriteLine("Mã Hàng: "+myOrder.ProductId);
            myWriter.WriteLine("Ngày Đặt Hàng: "+ myOrder.StartDate.ToString(Constants.FullYearToDate));
            myWriter.WriteLine("Ngày Hoàn Thành: "+myOrder.EndDate.ToString(Constants.FullYearToDate));
            myWriter.WriteLine("Số Lượng: "+myOrder.Quantity);
            myWriter.WriteLine("Thành Tiền: "+ (myOrder.Profit*myOrder.Quantity));
            myWriter.WriteLine("Thông Tin Khác:");
            myWriter.WriteLine(myOrder.Detail);
        }

        private void cbPdSelection_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(cbPdSelection.SelectedIndex == 0)
            {
                ReloadData();
            }
            else
            {
                DataSet pdDataSet = new DataSet();
                myDao.GetRemainProducts(ref pdDataSet);
                dtGridProducts.DataSource = pdDataSet.Tables[0];
                Utility.TransformProductTable(ref dtGridProducts, _role);
                dtGridProducts.Show();
            }
        }

        private void cbOrderSelection_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(cbOrderSelection.SelectedIndex == 0)
            {
                ReloadData();
            }
            else
            {
                DataSet temp = myDao.GetOrderWithStatus(cbOrderSelection.SelectedItem.ToString());
                dtGridOrders.DataSource = temp.Tables[0];
                Utility.TransformOrderTable(ref dtGridOrders);
                dtGridOrders.Show();
            }
        }
        #endregion
    }
}